/*
 * @author zz85 / https://github.com/zz85
 * @author mrdoob / http://mrdoob.com
 * Running this will allow you to drag three.js objects around the screen.
 */

THREE.DragControls = function ( _objects, _camera, _domElement,cssObjs ) {

	if ( _objects instanceof THREE.Camera ) {

		console.warn( 'THREE.DragControls: Constructor now expects ( objects, camera, domElement )' );
		var temp = _objects; _objects = _camera; _camera = temp;

	}
	//zlm
	var groupCss=[];
	var groupObj=[];
	var arr_bgColor=[];
	var hoverIndex=-1;
	var hoverBG;
	var clickedBG;
	var clickedIndex=-1;
	var groupid=-1;
	var bl_moving=false;

	var originOpacity=_objects[0].children[0].material.opacity;
	var hoverOpacity=0.2;
	var clickOpacity=1;
	//

	var _plane = new THREE.Plane();
	var _raycaster = new THREE.Raycaster();
	var _mouse = new THREE.Vector2();
	var _offset = new THREE.Vector3();
	var _intersection = new THREE.Vector3();
	var _selected = null, _hovered = null;
	//
	var scope = this;


	document.addEventListener("CloseNetElementInfo3D",function(){
		deactivate();
	})
	function activate() {
		// _domElement.addEventListener( 'mousemove', onDocumentMouseMove, false );
		// _domElement.addEventListener( 'mousedown', onDocumentMouseDown, false );
		// _domElement.addEventListener( 'mouseup', onDocumentMouseUp, false );
		// document.addEventListener( 'mousemove', onDocumentMouseMove, false );
		document.addEventListener( 'mousedown', onDocumentMouseDown, false );
		document.addEventListener( 'mouseup', onDocumentMouseUp, false );
		document.addEventListener( 'mousemove', onDocumentMouseMove, false );

		document.removeEventListener('mousedown',clickObj,false)
		document.removeEventListener( 'mousemove', hoverObj, false );
	}

	function deactivate() {
		// _domElement.removeEventListener( 'mousemove', onDocumentMouseMove, false );
		// _domElement.removeEventListener( 'mousedown', onDocumentMouseDown, false );
		// _domElement.removeEventListener( 'mouseup', onDocumentMouseUp, false );
		// document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
		document.removeEventListener( 'mousedown', onDocumentMouseDown, false );
		document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
		document.removeEventListener( 'mousemove', onDocumentMouseMove, false );

		document.addEventListener('mousedown',clickObj,false)
		document.addEventListener( 'mousemove', hoverObj, false );
	}
	function noOperation(){
		document.removeEventListener('mousedown',clickObj,false)
		document.removeEventListener( 'mousemove', hoverObj, false );
	}

	function dispose() {
		deactivate();
	}
	//模拟Hover单个网元


	function hoverObj(){
		event.preventDefault();
		_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
		_mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

		_raycaster.setFromCamera( _mouse, _camera );

		//CSSobj处理方法
		// var hoverTarget=_raycaster.intersectObjects(_objects,true);
		// if(hoverTarget.length>0) {
		// 	for(var w=0;w<cssObjs.length;w++){
		// 		if(cssObjs[w].name==hoverTarget[0].object.name&&hoverIndex==-1){
		// 			if(w!=clickedIndex) {
		// 				hoverIndex = w;
		// 				hoverBG = cssObjs[w].element.style.backgroundColor;
		// 				cssObjs[w].element.style.backgroundColor = "rgba(127,255,255,0.00)";
		// 			}
		// 			break;
		// 		}
		// 	}
		// }
		// else if(hoverIndex!=-1){
		// 	if(clickedIndex!=hoverIndex) {
		// 		cssObjs[hoverIndex].element.style.backgroundColor = hoverBG;
		// 	}
		// 	hoverIndex=-1;
		// }




		var hoverTarget=_raycaster.intersectObjects(_objects,true);

		if(hoverTarget.length>0) {
			// console.log("step0");
			var obj=hoverTarget[0].object.parent.children[0];
			var parent=hoverTarget[0].object.parent;
			if(hoverIndex==-1&&parent.index!=clickedIndex){
				hoverIndex=parent.index;
				hoverBG=obj.material.opacity;
				obj.material.opacity=0.2;

			}
		}
		else if(hoverIndex!=-1){
			// console.log("step2");
			if(clickedIndex!=hoverIndex) {
				_objects[hoverIndex].children[0].material.opacity=hoverBG;
			}
			hoverIndex=-1;
		}


	}

	function onDocumentMouseMove( event ) {

		event.preventDefault();
		_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
		_mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

		_raycaster.setFromCamera( _mouse, _camera );

		//******************
		//******************
		//******************
		//模拟Hover网元
		// var hoverTarget=_raycaster.intersectObjects(_objects,true);
		// if(hoverTarget.length>0) {
		// 	for(var w=0;w<cssObjs.length;w++){
		// 		if(cssObjs[w].name==hoverTarget[0].object.name&&groupid==-1){
		// 			for(var z=0;z<cssObjs.length;z++){
		// 				// console.log(cssObjs[z].groupid,cssObjs[w].groupid)
		// 				if(cssObjs[z].groupid==cssObjs[w].groupid){
		// 					cssObjs[z].element.style.backgroundColor = "rgba(127,255,255,0.00)";
		// 				}
		// 			}
		// 			groupid=1;
		// 			break;
		// 		}
		// 	}
		// }
		// else if(groupid!=-1&&!bl_moving){
		// 	for(var z=0;z<cssObjs.length;z++){
		// 			cssObjs[z].element.style.backgroundColor=arr_bgColor[z];
		// 	}
		// 	groupid=-1;
		// }

		var obj,parent;
		var hoverTarget=_raycaster.intersectObjects(_objects,true);
		if(hoverTarget.length>0) {
			obj=hoverTarget[0].object.parent.children[0];
			parent=hoverTarget[0].object.parent;
			for(var z=0;z<_objects.length;z++){
				if(_objects[z].groupid==parent.groupid){
					_objects[z].children[0].material.opacity=hoverOpacity;
				}
			}
			groupid=parent.groupid;
		}
		else if(groupid!=-1&&!bl_moving){
			for(var z=0;z<_objects.length;z++){
				_objects[z].children[0].material.opacity=originOpacity;
			}
			groupid=-1;
		}
		//******************
		//******************
		//******************



		var xx,yy,zz;
		var oldPosition=new THREE.Vector3();
		if ( _selected && scope.enabled ) {
			if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
				oldPosition.copy(_selected.position);
				_selected.position.copy( _intersection.sub( _offset ) );
				xx=_selected.position.x-oldPosition.x;
				yy=_selected.position.y-oldPosition.y;
				zz=_selected.position.z-oldPosition.z;
			}

			for(var z=0;z<cssObjs.length;z++){
				if(cssObjs[z].name==_selected.name){
					cssObjs[z].position.copy(_selected.position);
				}
			}

			for(var y=0;y<groupObj.length;y++){
				if(groupObj[y].name!=_selected.name) {
					groupObj[y].position.x += xx;groupObj[y].position.y += yy;groupObj[y].position.z += zz;
					groupCss[y].position.x += xx;groupCss[y].position.y += yy;groupCss[y].position.z += zz;
				}
			}
			scope.dispatchEvent( { type: 'drag', object: _selected } );
			return;
		}
		_raycaster.setFromCamera( _mouse, _camera );
		var intersects = _raycaster.intersectObjects( _objects,true );
		if ( intersects.length > 0 ) {
			var object = intersects[ 0 ].object.parent;
			_plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), object.position );
			if ( _hovered !== object ) {
				scope.dispatchEvent( { type: 'hoveron', object: object } );
				_domElement.style.cursor = 'pointer';
				_hovered = object;
			}
		} else {
			if ( _hovered !== null ) {
				scope.dispatchEvent( { type: 'hoveroff', object: _hovered } );
				_domElement.style.cursor = 'auto';
				_hovered = null;
			}
		}
	}

	var clickDelay=0.3;
	var clickTimes=0;
	var sameObj;
	//模拟Click网元
	function clickObj(event){
		// event.preventDefault();
		_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
		_mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
		_raycaster.setFromCamera( _mouse, _camera );
		var clickedTarget=_raycaster.intersectObjects(_objects,true);
		// if(clickedTarget.length>0) {
		// 	clickTimes++;
		// 	setTimeout(function () {
		// 		clickTimes = 0;
		// 	}, clickDelay * 1000);
        //
		// }
		// if (clickTimes >= 2) {//双击执行，取消选择
		// 	noOperation();
		// 	// console.log(clickedIndex)
		// 	cssObjs[clickedIndex].element.style.backgroundColor=arr_bgColor[clickedIndex];
		// 	document.dispatchEvent(new CustomEvent("ShowNetElementInfo", {detail: {"clickedIndex": clickedIndex, "b": 1}}));
		// }
		//  else if(clickedTarget.length>0) {//正常单击事件
		// 	for(var w=0;w<cssObjs.length;w++){
		// 		if(cssObjs[w].name==clickedTarget[0].object.name){
		// 			if(clickedIndex!=-1){//使得单击另外一个网元后，先前的网元变回原来的背景色
		// 				cssObjs[clickedIndex].element.style.backgroundColor=arr_bgColor[clickedIndex];
		// 			}
		// 			if(clickedIndex==w){//取消选中状态
		// 				cssObjs[clickedIndex].element.style.backgroundColor=arr_bgColor[clickedIndex];
		// 				// clickedIndex=-1;
		// 			}
		// 			else {
		// 				clickedIndex = w;
		// 				clickedBG = cssObjs[w].element.style.backgroundColor;
		// 				// console.log(clickedBG);
		// 				cssObjs[w].element.style.backgroundColor = "rgba(127,255,255,0.75)";
		// 			}
		// 			break;
		// 		}
		// 	}
		// }

		var obj;
		var parent;
		if(clickedTarget.length>0) {
			obj=clickedTarget[0].object.parent.children[0];
			parent=clickedTarget[0].object.parent;

			if(sameObj!=parent){
				sameObj=parent;
				clickTimes=1;
				setTimeout(function () {
					clickTimes = 0;
				}, clickDelay * 1000);
			}
			else{
				clickTimes++;
				setTimeout(function () {
					clickTimes = 0;
				}, clickDelay * 1000);
			}
		}
		if (clickTimes >= 2) {//双击执行，取消选择
			noOperation();
			obj=clickedTarget[0].object.parent.children[0];
			obj.material.opacity=originOpacity;
			document.dispatchEvent(new CustomEvent("ShowNetElementInfo", {detail: {"clickedIndex": clickedTarget[0].object.parent.index, "b": 1}}));
			clickedIndex=-1;
		}
		else if(clickedTarget.length>0) {//正常单击事件


			if(clickedIndex!=-1){
				_objects[clickedIndex].children[0].material.opacity=originOpacity;
			}
			if(clickedIndex==parent.index){
				_objects[clickedIndex].children[0].material.opacity=originOpacity;
				clickedIndex=-1;
			}
			else{
				clickedIndex=parent.index;
				clickedBG=obj.material.opacity;
				obj.material.opacity=0.8;
			}

			// for(var w=0;w<cssObjs.length;w++){
			// 	if(cssObjs[w].name==clickedTarget[0].object.name){
			// 		if(clickedIndex!=-1){//使得单击另外一个网元后，先前的网元变回原来的背景色
			// 			cssObjs[clickedIndex].element.style.backgroundColor=arr_bgColor[clickedIndex];
			// 		}
			// 		if(clickedIndex==w){//取消选中状态
			// 			cssObjs[clickedIndex].element.style.backgroundColor=arr_bgColor[clickedIndex];
			// 			// clickedIndex=-1;
			// 		}
			// 		else {
			// 			clickedIndex = w;
			// 			clickedBG = cssObjs[w].element.style.backgroundColor;
			// 			// console.log(clickedBG);
			// 			cssObjs[w].element.style.backgroundColor = "rgba(127,255,255,0.75)";
			// 		}
			// 		break;
			// 	}
			// }
		}



	}


	function onDocumentMouseDown( event ) {
		// event.preventDefault();
		_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
		_mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;


		_raycaster.setFromCamera( _mouse, _camera );
		var intersects = _raycaster.intersectObjects( _objects,true );
		if ( intersects.length > 0 ) {
			bl_moving=true;
			_selected = intersects[ 0 ].object.parent;

			groupObj=[];
			groupCss=[];

			for(var k=0;k<_objects.length;k++) {
				if (_objects[k].groupid == _selected.groupid) {
					groupObj.push(_objects[k]);
					groupCss.push(cssObjs[k]);
				}
			}
			if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) {
				_offset.copy( _intersection ).sub( _selected.position );
			}
			_domElement.style.cursor = 'move';
			scope.dispatchEvent( { type: 'dragstart', object: _selected } );
		}
	}

	function onDocumentMouseUp( event ) {
		event.preventDefault();
		if ( _selected ) {
			bl_moving=false;
			scope.dispatchEvent( { type: 'dragend', object: _selected } );
			_selected = null;
		}
		_domElement.style.cursor = 'auto';
	}

	function initial(){
		for(var z=0;z<cssObjs.length;z++){
			arr_bgColor.push(cssObjs[z].element.style.backgroundColor);
		}
	}


	initial();
	activate();
	// API
	this.enabled = true;
	this.activate = activate;
	this.deactivate = deactivate;
	this.dispose = dispose;

	// Backward compatibility

	this.setObjects = function () {
		console.error( 'THREE.DragControls: setObjects() has been removed.' );
	};

	this.on = function ( type, listener ) {
		console.warn( 'THREE.DragControls: on() has been deprecated. Use addEventListener() instead.' );
		scope.addEventListener( type, listener );
	};

	this.off = function ( type, listener ) {
		console.warn( 'THREE.DragControls: off() has been deprecated. Use removeEventListener() instead.' );
		scope.removeEventListener( type, listener );
	};

	this.notify = function ( type ) {
		console.error( 'THREE.DragControls: notify() has been deprecated. Use dispatchEvent() instead.' );
		scope.dispatchEvent( { type: type } );
	};
};

THREE.DragControls.prototype = Object.create( THREE.EventDispatcher.prototype );
THREE.DragControls.prototype.constructor = THREE.DragControls;
